package com.huge;

import java.util.BitSet;

/**
 * @author 小也
 * @create 2021/7/27 0:21
 */
public class BloomFilter {
    //数组大小
    private static final int SIZE = 2 << 24;

    //数组
    private BitSet bitSet = new BitSet(SIZE);

    //哈希函数的除数，建议取稍大的质数，避免位运算导致前几位特征值丢失
    private static final int[] hashNum = {13,29,37,51,79};

    //哈希函数
    private static int MyHash(int seed, Object value){
        int h;
        return (value == null) ? 0 : (SIZE - 1) & ((h = value.hashCode()) ^ (h >>> 16));
    }

    //添加
    public void addObject(Object value){
        for (int i : hashNum) {
            int temp = MyHash(i,value);
            bitSet.set(temp,true);
        }
        System.out.println("添加成功！");
    }

    //判断是否存在
    public boolean isContain(Object value){
        boolean result = true;
        for (int i : hashNum) {
            int temp = MyHash(i,value);
            result &= bitSet.get(temp);
        }
        return result;
    }


    public static void main(String[] args) {
        BloomFilter bloomFilter = new BloomFilter();
        System.out.println(bloomFilter.isContain("111222"));
        System.out.println(bloomFilter.isContain("111333"));
        bloomFilter.addObject("111222");
        bloomFilter.addObject("111333");
        System.out.println(bloomFilter.isContain("111222"));
        System.out.println(bloomFilter.isContain("111333"));
    }
}
